﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Web;

namespace CPAIS.Web.AjaxHandlers
{
    public class MenuTreeHandler : AjaxHandler
    {
        public MenuTreeHandler(HttpContext context) : base(context) { }

        /// <summary>
        /// Ajax Request: 
        ///     GetMenuTreeNodes
        /// Params:
        ///     Null
        /// Reponse:
        ///     Json - List<TreeNode>
        /// </summary>
        #region Ajax Request GetMenuTreeNodes

        public void GetMenuTreeNodes()
        {
            List<TreeNode> nodes = new List<TreeNode>();
            nodes.Add(new TreeNode
            {
                id = "overview",
                text = "Overview",
                leaf = true,
                iconCls = "o-icon-overview"
            });
            nodes.Add(new TreeNode
            {
                id = "upload",
                text = "Upload",
                leaf = true,
                iconCls = "o-icon-upload"
            });
            TreeNode eventLogNode = new TreeNode
            {
                id = "eventLogs",
                text = "Event Logs",
                leaf = false,
                expanded = false,
                children = new List<TreeNode>()
            };
            nodes.Add(eventLogNode);

            bool mode;
            List<string> eventLogNames = (Application[Constants.DSManager] as DSManager).ListsEventLogs(out mode);         
            eventLogNode.text += mode ? " (DB Mode)" : " (File Mode)";
            foreach (var fileName in eventLogNames)
            {
                var fileNode = new TreeNode();
                fileNode.id = fileName;
                fileNode.text = fileName;
                fileNode.leaf = true;
                fileNode.iconCls = "o-icon-xml";
                eventLogNode.children.Add(fileNode);
            }

            if (eventLogNode.children.Count != 0)
                eventLogNode.expanded = true;

            WriteJson(nodes);
        }

        private class TreeNode
        {
            public string id { get; set; }
            public string text { get; set; }
            public bool leaf { get; set; }
            public bool expanded { get; set; }
            public string iconCls { get; set; }
            public List<TreeNode> children { get; set; }
        }

        #endregion
    }
}